import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const Home = () => import('@/views/home')
const Requestion = () => import('@/views/requestion')
const User = () => import('@/views/user')
const Vedio = () => import('@/views/vedio')
const Search = () => import('@/views/search')
const SearchResult = () => import('@/views/search/result.vue')
const Article = () => import('@/views/article')
const Profile = () => import ('@/views/user/profile.vue')
const Chat = () => import ('@/views/user/chat.vue')
Vue.use(VueRouter)

// 将原型上原始的方法, 存到了一个变量中
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Login
    },
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: '',
          component: Home,
          meta: { isKeepAlive: true }
        },
        {
          path: 'requestion',
          component: Requestion
        },
        {
          path: 'user',
          component: User
        },
        {
          path: 'vedio',
          component: Vedio
        }
      ]
    },
    {
      path: '/search',
      component: Search
    },
    {
      path: '/searchResult',
      component: SearchResult
    },
    {
      path: '/article/:id',
      component: Article
    },
    {
      path: '/profile',
      component: Profile
    },
    {
      path: '/userchat',
      component: Chat
    }

  ]
})

const AuthUrls = ['/user']
router.beforeEach((to, from, next) => {
  const token = store.state.user.tokenInfo.token
  if (to.path === '/login' && token) {
    next('/')
    return
  }
  if (AuthUrls.includes(to.path)) {
    if (token) {
      next()
    } else {
      router.push({
        path: '/login',
        query: {
          // 传入参数
          backto: to.fullPath
        }
      })
    }
  } else {
    next()
  }
})

export default router
